<!-- 地图网格线交互处理 -->
<template>
  <div></div>
</template>

<script lang="ts">
import { Component, Watch } from "vue-property-decorator";
import Mixins from "./CMixins.vue";
import { getModules } from "~/assets/modules/arcgisAPI";
import store from "~/assets/modules/store";
import { searchFeatures, searchFields } from "@/assets/modules/areaUtils";
import EsriJSONUtils from "@/assets/modules/esriJSONUtils";
import { setFilter } from "@/assets/modules/esriLayer";
import exportVue from "@/assets/modules/exportVue";
@Component({ name: "GridHandler", components: {} })
export default class extends Mixins {
  // get gridmanData() {
  //   return this.$store.getters["videoData/gridmanData"];
  // }
  // get zlxmData() {
  //   return this.$store.getters["videoData/zlxmData"];
  // }
  // get zlqyData() {
  //   return this.$store.getters["videoData/zlqyData"];
  // }
  // get jjjgData() {
  //   return this.$store.getters["videoData/jjjgData"];
  // }
  get gridData() {
    return this.$store.getters['videoData/gridData']
  }
  get gridLastData() {
    return this.$store.getters['videoData/gridLastData']
  }
  // private gridmanGraphics: any[] = [];
  // private zlxmGraphics: any[] = [];
  // private zlqyGraphics: any[] = [];
  // private jjjgGraphics: any[] = [];
  get loaded2d() {
    return this.$store.getters["view/loaded2d"];
  }

  @Watch("loaded2d")
  handleLoaded2d() {
    if (this.loaded2d) {
      // this.addFeatureLayer("gridman", this.gridmanGraphics);
      // this.addFeatureLayer("zlxm", this.zlxmGraphics);
      // this.addFeatureLayer("zlqy", this.zlqyGraphics);
      // this.addFeatureLayer("jjjg", this.jjjgGraphics);
      // this.createGrid();
    }
  }
  async mounted() {
    this.handleAreaSelect();
    // if (store.gridmanLayer) {
    //   store.gridmanLayer.visible = true;
    // } else {
    //   this.createGraphic("gridman").then(graphics => {
    //     this.gridmanGraphics = graphics;
    //     this.addFeatureLayer("gridman", graphics);
    //   });
    // }
    // if (store.zlxmLayer) {
    //   store.zlxmLayer.visible = true;
    // } else {
    //   this.createGraphic("zlxm").then(graphics => {
    //     this.zlxmGraphics = graphics;
    //     this.addFeatureLayer("zlxm", graphics);
    //   });
    // }
    // if (store.zlqyLayer) {
    //   store.zlqyLayer.visible = true;
    // } else {
    //   this.createGraphic("zlqy").then(graphics => {
    //     this.zlqyGraphics = graphics;
    //     this.addFeatureLayer("zlqy", graphics);
    //   });
    // }
    // if (store.jjjgLayer) {
    //   store.jjjgLayer.visible = true;
    // } else {
    //   this.createGraphic("jjjg").then(graphics => {
    //     this.jjjgGraphics = graphics;
    //     this.addFeatureLayer("jjjg", graphics);
    //   });
    // }
    if (store.wgfwLayer) {
      store.wgfwLayer.visible = true;
      if (store.wgfwLabelLayer) {
        store.wgfwLabelLayer.visible = true;
      }
    // } else if (this.view) {
    //   this.createGrid();
    }
  }

  beforeDestroy() {
    if (this.view) {
      // if (store.gridmanLayer) {
      //   store.gridmanLayer.visible = false;
      // }
      // if (store.zlxmLayer) {
      //   store.zlxmLayer.visible = false;
      // }
      // if (store.zlqyLayer) {
      //   store.zlqyLayer.visible = false;
      // }
      // if (store.jjjgLayer) {
      //   store.jjjgLayer.visible = false;
      // }
      if (store.wgfwLayer) {
        store.wgfwLayer.visible = false;
      }
      if (store.wgfwLabelLayer) {
        store.wgfwLabelLayer.visible = false;
      }
    }
    this.destroy();
  }

  // // 创建点
  // async createGraphic(type: any) {
  //   const modules = await getModules(["esri/Graphic"]);
  //   const [Graphic] = modules;
  //   const graphics: any[] = [];
  //   if (type == "gridman") {
  //     this.gridmanData.forEach((el: any) => {
  //       const { point, sfid } = el;
  //       if (point) {
  //         const graphic = new Graphic({
  //           geometry: {
  //             x: point.x,
  //             y: point.y,
  //             type: "point",
  //             spatialReference: store.spatialReference
  //           },
  //           attributes: { objectId: sfid }
  //         });
  //         graphics.push(graphic);
  //       }
  //     });
  //   } else if (type == "zlxm") {
  //     this.zlxmData.forEach((el: any) => {
  //       const { xzb, yzb, sfid } = el;
  //       const graphic = new Graphic({
  //         geometry: {
  //           x: parseFloat(xzb),
  //           y: parseFloat(yzb),
  //           type: "point",
  //           spatialReference: store.spatialReference
  //         },
  //         attributes: { objectId: sfid }
  //       });
  //       graphics.push(graphic);
  //     });
  //   } else if (type == "zlqy") {
  //     this.zlqyData.forEach((el: any) => {
  //       const { xzb, yzb, sfid } = el;
  //       const graphic = new Graphic({
  //         geometry: {
  //           x: parseFloat(xzb),
  //           y: parseFloat(yzb),
  //           type: "point",
  //           spatialReference: store.spatialReference
  //         },
  //         attributes: { objectId: sfid }
  //       });
  //       graphics.push(graphic);
  //     });
  //   } else {
  //     this.jjjgData.forEach((el: any) => {
  //       const { zbx, zby, sfid } = el;
  //       const graphic = new Graphic({
  //         geometry: {
  //           x: parseFloat(zbx),
  //           y: parseFloat(zby),
  //           type: "point",
  //           spatialReference: store.spatialReference
  //         },
  //         attributes: { objectId: sfid }
  //       });
  //       graphics.push(graphic);
  //     });
  //   }
  //   return graphics;
  // }
  // // 创建网格边界
  // async createGrid() {
  //   const url = (window as any).urlConfig.grid.url;
  //   searchFeatures(url).then((res: any) => {
  //     if (res.length > 0) {
  //       const graphics = res.map((el: any) => {
  //         const feature = el.clone();
  //         return feature;
  //       });
  //       const graphics2 = res.map((el: any) => {
  //         el.geometry = el.geometry.centroid.clone();
  //         const feature = el.clone();
  //         return feature;
  //       });
  //       searchFields(url).then((fields: any) => {
  //         // this.addFeatureLayerGrid(graphics, fields);
  //         // this.addFeatureLayerGridLabel(graphics2, fields);
  //       });
  //     }
  //   });
  // }
  // // 添加图层
  // async addFeatureLayer(type: string, graphics: any[]) {
  //   if (!this.view) {
  //     return;
  //   }
  //   const modules = await getModules(["esri/layers/FeatureLayer"]);
  //   const [FeatureLayer] = modules;
  //   const layer = new FeatureLayer({
  //     spatialReference: store.spatialReference,
  //     source: graphics.map(el => {
  //       return el.clone();
  //     }),
  //     fields: [
  //       {
  //         name: "objectId",
  //         alias: "objectId",
  //         type: "oid"
  //       }
  //     ],
  //     objectIdField: "objectId",
  //     geometryType: "point",
  //     elevationInfo: { mode: "relative-to-ground", offset: 20 },
  //     renderer: {
  //       type: "simple",
  //       symbol: this.getSymbol(type)
  //     }
  //   });
  //   this.view.map.add(layer);
  //   if (type == "gridman") {
  //     store.gridmanLayer = layer;
  //   } else if (type == "zlxm") {
  //     store.zlxmLayer = layer;
  //   } else if (type == "zlqy") {
  //     store.zlqyLayer = layer;
  //   } else {
  //     store.jjjgLayer = layer;
  //   }
  // }
  // // 添加图层
  // async addFeatureLayerGrid(graphics: any[], fields: any[]) {
  //   if (!this.view) {
  //     return;
  //   }
  //   const modules = await getModules(["esri/layers/FeatureLayer"]);
  //   const [FeatureLayer] = modules;
  //   const layer = new FeatureLayer({
  //     spatialReference: store.spatialReference,
  //     source: graphics.map(el => {
  //       return el.clone();
  //     }),
  //     fields: fields,
  //     objectIdField: "objectid",
  //     geometryType: "polygon",
  //     elevationInfo: { mode: "relative-to-ground", offset: 20 },
  //     renderer: {
  //       type: "simple",
  //       symbol: {
  //         type: "simple-fill",
  //         style: "solid",
  //         color: [227, 139, 79, 0],
  //         outline: {
  //           color: "#0d8e0d",
  //           width: 2
  //         }
  //       }
  //     }
  //   });
  //   this.view.map.add(layer);
  //   store.wgfwLayer = layer;
  // }
  // // 添加图层
  // async addFeatureLayerGridLabel(graphics: any[], fields: any[]) {
  //   if (!this.view) {
  //     return;
  //   }
  //   const modules = await getModules(["esri/layers/FeatureLayer"]);
  //   const [FeatureLayer] = modules;
  //   const name = "$feature.wgname";
  //   const nameClass = {
  //     where: "1=1",
  //     labelPlacement: "center-center",
  //     labelExpressionInfo: {
  //       expression: name
  //     },
  //     symbol: {
  //       type: "text",
  //       color: "black",
  //       haloColor: "white",
  //       haloSize: 2,
  //       font: {
  //         size: 14
  //       }
  //     },
  //     minScale: 45000
  //   };
  //   const layer = new FeatureLayer({
  //     spatialReference: store.spatialReference,
  //     source: graphics.map(el => {
  //       return el.clone();
  //     }),
  //     fields: fields,
  //     objectIdField: "objectid",
  //     geometryType: "point",
  //     elevationInfo: { mode: "relative-to-ground", offset: 20 },
  //     labelingInfo: [nameClass],
  //     renderer: {
  //       type: "simple",
  //       symbol: {
  //         type: "simple-marker",
  //         size: 6,
  //         outline: null,
  //         color: [255, 255, 255, 0]
  //       }
  //     }
  //   });
  //   this.view.map.add(layer);
  //   store.wgfwLabelLayer = layer;
  //   console.log(store.wgfwLabelLayer);
  // }
  // // 二三维使用不同的样式
  // private getSymbol(type: string) {
  //   const img =
  //     type == "gridman"
  //       ? require("@/assets/images/points/fangguanyuan.png")
  //       : type == "zlxm"
  //       ? require("@/assets/images/points/zulinxiangmu.png")
  //       : type == "zlqy"
  //       ? require("@/assets/images/points/zulinqi.png")
  //       : require("@/assets/images/points/jingjijigou.png");
  //   return {
  //     type: "picture-marker",
  //     url: img,
  //     width: "28px",
  //     height: "37px",
  //     yoffset: "20px"
  //   };
  // }

  handleAreaSelect() {
    console.log('handleAreaSelect')
    // 按行政区区、县、街道级选中事件
    exportVue.$on("area-select", (param: any) => {
      this.drawGraphic(
        param.url,
        param.name,
        param.nameField,
        param.codeField,
        param.type,
        param.sqCodeList
      );
    });
    // 按行政区市级选中事件
    exportVue.$on("area-select-city", (url: any) => {
      this.addCityGraphic(url);
      const areaData = {
        areaCode: "",
        gridId: "",
        gridName: "",
        queryType: 0,
        sqCodeList: "",
        geoJson: "",
        areaType: 0,
        areaName: "厦门市",
        qjmc: ""
      };
      console.log(areaData);
      this.$store.commit("videoData/setAreaData", areaData);
      // this.setAllFeatureLayerFilter();
    });
    // 按网格市级选中事件
    exportVue.$on("grid-select-city", () => {
      const areaData = {
        areaCode: "",
        gridId: "",
        gridName: "厦门市",
        queryType: 1,
        sqCodeList: "",
        geoJson: "",
        areaType: 0,
        areaName: "",
        qjmc: ""
      };
      console.log(areaData);
      this.$store.commit("videoData/setAreaData", areaData);
      // this.setAllFeatureLayerFilter();
      this.setGridLayerFilter();
      this.getGridGemotry('厦门市', "qjmc", 1);
    });
    // 按网格区级选中事件
    exportVue.$on("grid-select-qjmc", (qjmc: any) => {
      this.setGridLayerFilter(undefined, qjmc);
      this.getGridGemotry(qjmc, "qjmc", 1);
    });
    // 按网格县级选中事件
    exportVue.$on("grid-select", (wgid: any) => {
      this.setGridLayerFilter(wgid);
      this.getGridGemotry(wgid, "wgid", 2);
    });
  }
  // 添加厦门市行政区划
  async addCityGraphic(url: any) {
    if (!this.view) {
      return;
    }
    searchFeatures(url).then((res: any) => {
      if (res.length > 0) {
        this.addGraphics(res);
      } else {
        this.clearGraphic();
      }
    });
  }
  // 添加区、县、街道级行政区划
  async drawGraphic(
    url: any,
    name: any,
    nameField: string,
    codeField: string,
    type: number,
    sqCodeList: any
  ) {
    if (!this.view) {
      return;
    }
    const modules = await getModules(["esri/Graphic"]);
    const [Graphic] = modules;
    const where = `OBJECTID=${name}`;
    searchFeatures(url, where).then((res: any) => {
      if (res.length > 0) {
        const geometry = res[0].geometry;
        this.view.graphics.removeAll();
        if (geometry) {
          const fillSymbol = {
            type: "simple-fill",
            color: [227, 139, 79, 0.1],
            outline: {
              color: [227, 139, 79, 0.8],
              width: 2
            }
          };
          const graphic = new Graphic({
            geometry,
            symbol: fillSymbol
          });
          this.view.graphics.add(graphic);
          const pointGraphic = new Graphic({
            geometry: geometry.centroid,
            symbol: this.getTextSymbol(res[0].attributes[nameField])
          });
          pointGraphic.id = name;
          pointGraphic.name = res[0].attributes[nameField];
          this.view.graphics.add(pointGraphic);
          this.view.goTo({
            target: geometry
          });
          // geometry转geojson
          const geoJson = JSON.stringify(
            EsriJSONUtils.esriJSONToGeoJSON(geometry)
          );
          const areaData = {
            areaCode: res[0].attributes[codeField],
            gridId: "",
            gridName: "",
            queryType: 0,
            sqCodeList: sqCodeList,
            geoJson: geoJson,
            areaType: type,
            areaName: res[0].attributes[nameField],
            qjmc: res[0].attributes.QJMC
          };
          console.log(areaData);
          this.$store.commit("videoData/setAreaData", areaData);
          // this.setAllFeatureLayerFilter(geometry);
        }
      }
    });
  }
  // 网格图层过滤参数
  setGridLayerFilter(wgid?: any, qjmc?: any) {
    console.log('setGridLayerFilter')
    if (store.wgfwLayer) {
      let where = "1=1";
      if (wgid) {
        where = "wgid = '" + wgid + "'";
      }
      if (qjmc) {
        where = "qjmc = '" + qjmc + "'";
      }
      const param = {
        layer: store.wgfwLayer,
        where: where,
        geometry: undefined,
        view: this.view
      };
      setFilter(param);
    }
    if (store.wgfwLabelLayer) {
      let where = "1=1";
      if (wgid) {
        where = "wgid = '" + wgid + "'";
      }
      if (qjmc) {
        where = "qjmc = '" + qjmc + "'";
      }
      const param = {
        layer: store.wgfwLabelLayer,
        where: where,
        geometry: undefined,
        view: this.view
      };
      setFilter(param);
    }
  }
  // 添加网格图形
  async getGridGemotry(name: any, field: string, type: number) {
    const loading = this.$loading({
      lock: true,
      text: '地图加载中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    if (!this.view) {
      return;
    }
    const modules = await getModules(["esri/geometry/geometryEngine", "esri/geometry/Point", "esri/geometry/Polygon", 'esri/Graphic']);
    const [geometryEngine, Point, Polygon, Graphic] = modules;
    this.view.graphics.removeAll()
    const filterData = name == '厦门市' ? this.gridLastData : this.gridLastData.filter((item: any) => {
      return item[field == 'wgid' ? 'gridId' : 'qjmc'] == name;
    })
    console.log('filterData', filterData)
    filterData.forEach((data: any, index: any) => {
      const wgGeometry = new Polygon({
        id: 'wgGeometry',
        type: "polygon",
        rings: EsriJSONUtils.geoJSONToEsriJSON(data.geoJsonObject).rings
      })
      const fillSymbol = {
        type: 'simple-fill',
        color: [0, 0, 0, 0],
        outline: {
          color: '#0d8e0d',
          width: 2
        }
      }
      const wgGraphics = new Graphic({
        geometry: wgGeometry,
        symbol: fillSymbol
      })
      this.view.graphics.add(wgGraphics)
    })
    this.$nextTick(() => {
      if (name == '厦门市') {
        const initialExtent2d = this.$store.getters["view/initialExtent2d"];
        this.view.extent = {
          xmin: initialExtent2d.xMin,
          xmax: initialExtent2d.xMax,
          ymin: initialExtent2d.yMin,
          ymax: initialExtent2d.yMax,
          spatialReference: this.view.spatialReference
        };
      } else {
        const wgGeometryRings = filterData.map((item: any) => {
          return EsriJSONUtils.geoJSONToEsriJSON(item.geoJsonObject).rings
        })
        const wgGeometry = geometryEngine.union(
          wgGeometryRings.map((rings: any) => {
            return new Polygon({
              id: 'wgGeometry',
              type: "polygon",
              rings: rings
            })
          })
        )
        const wgCenter = new Point({
          x: wgGeometry.centroid.x,
          y: wgGeometry.centroid.y,
          spatialReference: store.spatialReference
        })
        this.view.goTo({ center: wgCenter, scale: field == 'wgid' ? 100000 : 120000 })
      }
      loading.close();
    })
    const areaData = {
      areaCode: "",
      gridId: type == 2 ? name : "",
      gridName: type == 1 ? name : "",
      queryType: 1,
      sqCodeList: "",
      geoJson: '',
      areaType: type,
      areaName: type == 1 ? name : "",
      qjmc: ""
    };
    console.log(areaData);
    this.$store.commit("videoData/setAreaData", areaData);
    // const where = name == '厦门市' ? '1=1' : `${field}='${name}'`;
    // const url = (window as any).urlConfig.grid.url;
    // searchFeatures(url, where).then((res: any) => {
    //   loading.close();
    //   if (res.length > 0) {
    //     const geometries = res.map((item: any) => {
    //       return item.geometry;
    //     });
    //     const geometry = geometryEngine.union(geometries);
    //     // geometry转geojson
    //     const geoJson = JSON.stringify(
    //       EsriJSONUtils.esriJSONToGeoJSON(geometry)
    //     );
    //     const areaData = {
    //       areaCode: "",
    //       gridId: type == 2 ? name : "",
    //       gridName: type == 1 ? name : "",
    //       queryType: 1,
    //       sqCodeList: "",
    //       geoJson: geoJson,
    //       areaType: type,
    //       areaName: type == 1 ? name : "",
    //       qjmc: ""
    //     };
    //     console.log(areaData);
    //     this.$store.commit("videoData/setAreaData", areaData);
    //     // this.setAllFeatureLayerFilter(geometry);
    //   } else {
    //     const areaData = {
    //       areaCode: "",
    //       gridId: type == 2 ? name : "",
    //       gridName: type == 1 ? name : "",
    //       queryType: 1,
    //       sqCodeList: "",
    //       geoJson: "",
    //       areaType: type,
    //       areaName: type == 1 ? name : "",
    //       qjmc: ""
    //     };
    //     console.log(areaData);
    //     this.$store.commit("videoData/setAreaData", areaData);
    //   }
    // });
  }
  // setAllFeatureLayerFilter(geometry?: any) {
  //   this.setFeatureLayerFilter(store.gridmanLayer, geometry);
  //   this.setFeatureLayerFilter(store.zlxmLayer, geometry);
  //   this.setFeatureLayerFilter(store.zlqyLayer, geometry);
  //   this.setFeatureLayerFilter(store.jjjgLayer, geometry);
  // }
  // setFeatureLayerFilter(layer: any, geometry: any) {
  //   if (layer) {
  //     const param = {
  //       layer: layer,
  //       where: "1=1",
  //       geometry: geometry ? geometry : undefined,
  //       view: this.view
  //     };
  //     setFilter(param);
  //   }
  // }
}
</script>

<style lang="scss" scoped></style>
